package activity_trabalhos;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import com.adjt.droidsapiens.R;

import database.DatabaseConnector;

public class NovoTrabalho extends Activity {
	
	Time time;
	Intent it;
	int semestreAtual;

	DatabaseConnector db;
	Cursor c;
	
	EditText nome, valor, local, data, hora;
	Spinner disciplinaSpinner;
	ArrayAdapter<String> disciplinaAdapter;
	Map<String, Integer> disciplinaMap = new HashMap<String, Integer>();
	
	private int mYear, mMonth, mDay, mHour, mMinute;
	int Year, Month, Day, Hour, Minute;
	
	public static final int Date_dialog_id = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_novo_trabalho);
		
		semestreAtual = getIntent().getIntExtra("semestreAtual", 0);
		nome = (EditText) findViewById(R.id.NovaTrabalho_nome);
		valor = (EditText) findViewById(R.id.NovaTrabalho_valor);
		local = (EditText) findViewById(R.id.NovaTrabalho_local);
		data = (EditText) findViewById(R.id.NovaTrabalho_data);
		data.setKeyListener(null);
		hora = (EditText) findViewById(R.id.NovaTrabalho_hora);
		hora.setKeyListener(null);
		disciplinaSpinner = (Spinner) findViewById(R.id.NovaTrabalho_disciplina);
		
		db = new DatabaseConnector(getBaseContext());
		db.open();
		String tables = "Disciplina";
		String[] column = new String[]{"idDisciplina", "nome"};
		String where = "";
		String orderBy = "";
		c = db.buscar(tables, column, where, orderBy);
		int idDisciplina;
		String nomeDisciplina;
		disciplinaAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item);
		if(c.getCount() > 0) {
			while(c.moveToNext()) {
				idDisciplina = c.getInt(c.getColumnIndex("idDisciplina"));
				nomeDisciplina = c.getString(c.getColumnIndex("nome"));
				disciplinaMap.put(nomeDisciplina, idDisciplina);
				disciplinaAdapter.add(nomeDisciplina);
			}
			disciplinaSpinner.setAdapter(disciplinaAdapter);
		}else {
			Toast.makeText(getBaseContext(), R.string.Toast_erroPrecisaDisciplinaCadastrada, Toast.LENGTH_LONG).show();
			Intent it = new Intent(getBaseContext(), Trabalhos.class);
			startActivity(it);
			it.putExtra("semestreAtual", semestreAtual);
			finish();
		}
		db.close();
	}
	
	public void getTime(){
		time = new Time(Time.getCurrentTimezone());
		time.normalize(true);
		time.setToNow();
		mYear = time.year;
		mMonth = time.month;
		mDay = time.monthDay;
		mHour = time.hour;
		mMinute = time.minute;
	}
	
	public void AdicionarTrabalho(View v) {
		if (nome.getText().length() > 0 && data.getText().length() > 0 && hora.getText().length() > 0) {
			db.open();
			String tables = "Atividade";
			ContentValues valores = new ContentValues();
			valores.put("tipo", 2);
			Time time = new Time();
			time.set(0, Minute, Hour, Day, Month, Year);
			time.normalize(true);
			valores.put("data", time.toMillis(true));
			if(valor.getText().length() > 0) {
				int temp = Integer.parseInt(valor.getText().toString());
				valores.put("valor", temp);
			}
			valores.put("local", local.getText().toString());
			valores.put("nome", nome.getText().toString());
			valores.put("idDisciplina", disciplinaMap.get(disciplinaSpinner.getSelectedItem().toString()));
			valores.put("idSemestre", semestreAtual);
			Long id = db.inserir(tables, valores);
			
			if(id != null) {
				Toast.makeText(getBaseContext(), "Trabalho Inserida com sucesso", Toast.LENGTH_LONG).show();
			}else
				Toast.makeText(getBaseContext(), "Ocorreu um erro ao inserir este trabalho, contate os desenvolvedores", Toast.LENGTH_LONG).show();
			db.close();
			Intent it = new Intent(getBaseContext(), Trabalhos.class);
			it.putExtra("semestreAtual", this.semestreAtual);
			startActivity(it);
			finish();
		} else Toast.makeText(getBaseContext(), R.string.Toast_camposNomeDataHoraObrigatorios, Toast.LENGTH_LONG).show();
	}
	
	@Override
	public void onBackPressed(){
		it = new Intent(getBaseContext(), Trabalhos.class);
		it.putExtra("semestreAtual", semestreAtual);
		startActivity(it);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.novo_trabalho, menu);
		return true;
	}
	
	public void DataDialog(View v) {
		getTime();
		DatePickerDialog DPD = new DatePickerDialog(NovoTrabalho.this, DateSetListener, mYear, mMonth, mDay);
		DPD.show();
	}
	
	public void HoraDialog(View v) {
		getTime();
		TimePickerDialog TPD = new TimePickerDialog(NovoTrabalho.this, HourSetListener, mHour, mMinute, true);
		TPD.show();
	}

	@Override
	@Deprecated
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);

		((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
		
		((TimePickerDialog) dialog).updateTime(mHour, mMinute);

	}

	private DatePickerDialog.OnDateSetListener DateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Year = year;
			Month = monthOfYear;
			Day = dayOfMonth;
			updateDisplayDate();
		}
	};

	private TimePickerDialog.OnTimeSetListener HourSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hour, int minute) {
			Hour = hour;
			Minute = minute;
			updateDisplayHour();
		}
	};

	private void updateDisplayDate() {
		// TODO Auto-generated method stub
		String month = "" + (Month + 1);
		if (Month < 9)
			month = "0" + (Month + 1);
		String day = "" + Day;
		if (Day < 10)
			day = "0" + Day;
		// Month is 0 based so add 1
		data.setText(new StringBuilder().append(day).append("/").append(month)
				.append("/").append(Year));
	}

	private void updateDisplayHour() {
		// TODO Auto-generated method stub
		String hour = "" + Hour;
		if (Hour < 10)
			hour = "0" + Hour;
		String minute = "" + Minute;
		if (Minute < 10)
			minute = "0" + Minute;
		hora.setText(new StringBuilder().append(hour).append(":")
				.append(minute));
	}
}
